package com.antdant.service;

import com.antdant.entity.Rank;
import com.antdant.repository.RankRepository;
import com.antdant.utils.DataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Lee Yunc
 * @Date 2021/3/9 9:33
 * @Description:
 * @Version 1.0
 */
@Slf4j
@Service
public class RankService {

    @Resource
    private RankRepository rankRepository;

    /**
     * 通过rankCode查询段位信息
     *
     * @param rankCode
     * @return
     */
    public Rank getRankByRankCode(Integer rankCode) {
        return rankRepository.findByRankCode(rankCode);
    }

    /**
     * 查询所有段位信息
     *
     * @param current
     * @param size
     * @return
     */
    public Page<Rank> getRanks(Integer current, Integer size, Rank rank) {
        Pageable pageable = PageRequest.of(current - 1, size);
        return rankRepository.findAll(new Specification<Rank>() {
            @Override
            public Predicate toPredicate(Root<Rank> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if (DataUtils.isNotEmptyStr(rank.getBeltName())) {
                    list.add(criteriaBuilder.like(root.get("beltName"), rank.getBeltName()));
                }
                if (DataUtils.isNotEmptyStr(rank.getGrade())) {
                    list.add(criteriaBuilder.like(root.get("grade"), rank.getGrade()));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        }, pageable);
    }

    /**
     * 通过段位查询段位码
     *
     * @param grade
     * @return
     */
    public Integer getRankCodeByGrade(String grade) {
        return rankRepository.findRankCodeByGrade(grade);
    }
}
